<!-- 课程新增、编辑 -->
<template>
  <el-card class="app-container">
    <div>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="140px"
        label-suffix=":"
      >
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item label="课程简介" prop="description">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4 }"
            v-model="form.description"
            placeholder="请输入课程简介"
          />
        </el-form-item>
        <el-form-item label="教师选择" prop="teacherName">
          <el-select
            ref="selectLabel"
            v-model="form.teacherName"
            clearable
            placeholder="请选择教师"
            @change="selectHandle"
          >
            <el-option
              v-for="item in teacher"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上课时间" prop="startTime">
          <el-date-picker
            v-model="startTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            @change="changeTimeHandle"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="学员选择" prop="recoveryName">
          <el-select
            ref="studentName"
            v-model="form.recoveryReceivers"
            value-key="id"
            multiple
            placeholder="请选择学员"
            @change="studentHandle"
          >
            <el-option
              v-for="item in student"
              :key="item.id"
              :label="item.recoveryName"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上课内容" prop="content">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4 }"
            v-model="form.content"
            placeholder="请输上课内容"
          />
        </el-form-item>
        <!-- 仅编辑可见 -->
        <template v-if="$route.query.id">
          <el-form-item ref="pic" label="上传课堂照片" prop="photos">
            <picture-upload
              v-model="form.photos"
              :limit="9"
              type="photos"
              path="appliance"
              :value="form.photos"
              :multiple="true"
              :file-list="photosfileList"
              @del-picture="delPicture"
              @add-picture="addPicture"
            ></picture-upload>
          </el-form-item>
          <el-form-item ref="video" label="上传短视频" prop="videos">
            <video-upload
              v-model="form.videos"
              :limit="1"
              type="video"
              path="appliance"
              :value="form.videos"
              :file-list="videosfileList"
              >
            </video-upload>
          </el-form-item>
        </template>
        <el-form-item label="课堂总结" prop="summary">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4 }"
            v-model="form.summary"
            placeholder="请输课堂总结"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="$router.go(-1)">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>
<script>
export default {
  name: "curriculumEdit",
  data() {
    var validata = (rule, value, callback) => {
      if (!this.form.photos && !this.form.videos) {
        callback(new Error("请至少填写一项"));
      } else {
        //  清除
        if (!this.form.photos || !this.form.videos) {
          this.$refs.pic.clearValidate();
          this.$refs.video.clearValidate();
        }
        callback();
      }
    };
    return {
      value1: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
      fileList: [],
      videosfileList: [],
      videoAccept: "video",
      videoFlag: false,
      photosfileList: [],
      startTime: [],
      student: [], //学员
      teacher: [], //教师
      studentEdit: [], //编辑时的学员数据
      videoStr:null,//视频地址
      form: {
        id: 0,
        institutionId: 0,
        institutionName: "",
        userId: 0,
        teacherId: 0,
        teacherName: "",
        name: "",
        description: "",
        startTime: "",
        endTime: "",
        content: "",
        photos: "",
        videos: "",
        summary: "",
        createTime: "",
        recoveryReceivers: [],
      },
      // 学员信息
      recovervReceivers: [],
      rules: {
        name: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
        description: [
          { required: true, message: "请输入关键词", trigger: "blur" },
        ],
        content: [{ required: true, message: "请输入关键词", trigger: "blur" }],
        teacherName: [
          { required: true, message: "请选择教师", trigger: "change" },
        ],
        // recoveryName:[{ required: true, message: "请选择学员", trigger: "change" }],
        photos: [{ required: true, message: "请上传照片", trigger: "change" }],
        startTime: [
          { required: true, message: "请选择上课时间", trigger: "change" },
        ],
        summary: [
          { required: true, message: "请输入课堂总结", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    getInfo() {
      this.API.deleteRecoveryInstitutionById().then((res) => {
        this.form.institutionId = res.data.id;
        this.getStudent(this.form.institutionId);
        this.getTeacher(this.form.institutionId);
      });
    },

    // 获取学员信息
    getStudent(id) {
      this.API.getRecoveryReceivers({ institutionId: id }).then((ret) => {
        console.log("学员：", ret);
        this.student = ret.data;
      });
    },

    //获取教师信息
    getTeacher(id) {
      this.API.getRecoveryTeacherList({ institutionId: id }).then((ret) => {
        console.log("教师:", ret.data); //[{id:1,name:'111'}] 数据是数组可直接渲染取值
        this.teacher = ret.data;
      });
    },
    selectHandle(e) {
      this.$nextTick(() => {
        this.form.teacherId = e;
        this.form.teacherName = this.$refs.selectLabel.selected.label; //获取选中的label
        console.log("selectHandle:", e, this.form.teacherName);
      });
    },
    // 上课时间
    changeTimeHandle(e) {
      console.log("changeTimeHandle:", e);
      // ["2023-07-09 02:00:02","2023-07-09 04:02:04"]
      this.form.startTime = e[0];
      this.form.endTime = e[1];
      // console.log('s:',this.form.startTime,'e:',this.form.endTime);
    },
    // 学生选择
    studentHandle(e) {
      this.$nextTick(() => {
        console.log("ee:", e);
      });
    },
    onSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log("onSubmit:", this.form);
          this.API.addOrUpdateRecoveryCourse({ body: this.form })
            .then((res) => {
              this.success("提交成功!");
              this.$router.go(-1);
            })
            .catch((err) => this.warning(err));
        } else {
          return false;
        }
      });
    },
    addPicture(res) {
      // this.photosfileList.push(res);
    },
    delPicture(field, list) {
      // this.form[field] = list;
    },
  },
  mounted() {
    this.getInfo();
    console.log("this.$route.query.id", this.$route.query.id);
    if (this.$route.query.id) {
      this.API.getRecoveryCourseById({ id: this.$route.query.id }).then(
        (ret) => {
          let tval = JSON.parse(JSON.stringify(ret.data));
          tval.recoveryReceivers = [];
          this.form = tval;
          this.startTime = [ret.data.startTime, ret.data.endTime];
          let self = this;
          setTimeout(function () {
            let currentStudent = ret.data.recoveryReceivers; //查询到的学员信息
            for (let i = 0; i < currentStudent.length; i++) {
              for (let j = 0; j < self.student.length; j++) {
                if (currentStudent[i].applyId === self.student[j].id) {
                  self.form.recoveryReceivers.push(self.student[j]);
                  break;
                }
              }
            }
          }, 2000);
        }
      );
    }
  },
};
</script>
  <style scoped lang="scss">
.app-container {
  padding-top: 20px;
  padding-right: 50px;

  .el-input {
    width: 400px;
  }

  .el-select {
    width: 300px;
  }
}
</style>